$(function () {

    var obj;
    var s = true;
    $('body').on('click','.toQuestionPopBtn',function () {//
        var teacherId = $(this).data('id');
        var isquestion = $(this).data('isquestion');
        var questionfee = $(this).data('questionfee');
        var name = $(this).data('name');
        goQuestionFn(teacherId,questionfee,isquestion,name);
        setTimeout(function(){
            obj = uploadImgFile({
                selectObj:'#question-upload-box',
                imgNum:4,
                param:'qaImg',
                previewCallback:function (file,src) {
                    $("#tqImgWrap").append('<span><em class="wm-close-em" data-id="'+file.id+'"><i class="iconfont icon-guanbi"></i></em><img src="'+src+'" width="80px" height="50px"/></span>');
                    $("#def-span-box").hide();
                },
                uploadFinished:function (urlList) {
                    var imageUrls="";
                    $.each(urlList,function (index, e) {
                        if(index < urlList.length -1){
                            imageUrls+= e+",";
                        }else{
                            imageUrls+= e;
                        }
                    });
                    $("#imageStr").val(imageUrls);
                    _saveQa();
                }
            });

        },500)
    }).on("click","#save-question",function () {
        saveQuestion();
    }).on('click','.close-popup',function () {//关闭提问弹框后，销毁uploader
        obj.destroy();
    }).on('click','i.icon-guanbi',function () {
        var _obj = $(this).parent();
        var fileId = _obj.data('id');
        deleteFile(fileId, function () {
            _obj.parent().remove();
            //获取初化状态的文件
            var files = obj.getFiles('inited');
            //如果队列中没有文件
            if(files.length<=0){
                $("#def-span-box").show();
            }
        })
    }).on('keyup','textarea[name="context"]',function(){
        var that =$(this);
        if(that.val().replace(/\s/g,"").length>200){
            var blankSize =that.val().length-that.val().replace(/\s/g,"").length;
            that.val( that.val().substring(0,200+blankSize));
            $.toast("最多可输入200个字");
        }
    });

    //提问方法
    function saveQuestion() {
        var context = $('textarea[name="context"]').val();
        if(context == '' || context == null){
            $.toast("问题内容不能为空");
            return false;
        }
        if(!s){
            return;
        }
        s = false;
        //判断是否有图片上传
        var files = obj.getFiles('inited');
        if(files.length>0){//有文件先上传文件
            $("#tqImgWrap>span>em").remove();
            obj.upload();
        }else{//没有文件可直接保存问答内容
            _saveQa();
        }
    }

    //提问方法
    function _saveQa() {
        if($('textarea[name="context"]').val().replace(/\s/g,"").length>200){
            s=true;
            $.toast("最多可输入200个字");
            return false;
        }
         var isquestion =$("#isQuestion").val();
         var  questionfee =$("#questionFee").val();
         var  teacher_name =$("#teacher_name").val();
        if(isquestion==1){

            var  content='本次向'+teacher_name+'提问，需支付'+questionfee+'元，<br/>确认支付吗';
            if(questionfee<=0){
                content = '本次向'+teacher_name+'提问，本次免费，确认提交问题,<br/>前往本次提问详情';
            }
            $.confirm(content, function () {
                saveQaData();
            },function(){
                s = true;
            });
        }else{
            saveQaData();
        }
    }

    function saveQaData() {
        var _value = $("#privacy").is(":checked");
        if(_value){
            $("input[name='privacy']").val(2);
        }else{
            $("input[name='privacy']").val(1);
        }
        //去获取图片url*/
       var data = $("#question-form").serializeJSON();
        if(GetQueryString("isCourse")!=null&&GetQueryString("isCourse")=="true"){
            data.isFree=1;
        }else{
            data.isFree=2;
        }
      var packageId =  GetQueryString("packageId");
        if(packageId!=null&&packageId!=0){
            data.packageId=packageId;
        }
        var courseId =  GetQueryString("courseId");
        if(courseId!=null&&courseId!=0){
            data.courseId=courseId;
        }
        var catalogId =  GetQueryString("catalogId");
        if(catalogId!=null&&catalogId!=0){
            data.catalogId=catalogId;
        }
        $.ajax({
            url: baseloaction + "/mobile/uc/qa/saveQuestion",
            data:JSON.stringify(data),
            type:"post",
            dataType:"json",
            contentType: 'application/json;charset=utf-8',
            success:function (result) {
                var isFree = result.entity.isFree;
                if (isFree == 1){
                    $.toast(result.message);
                }
                setTimeout(function(){
                    if(result.success){
                        var qa = result.entity;
                        if(qa.price>0){
                            window.location.href = baseloaction +'/mobile/uc/order/initPayOrder?orderType=COMMON&shopData='+qa.id+'-QA-1';
                        }else{
                            window.location.href = baseloaction +'/mobile/qa/questionInfo?questionId='+qa.id;
                        }
                    }else {
                        s = true;
                    }
                },1000);

            },
            error:function (error) {
                s = true;
                $.toast("系统繁忙，请稍后重试");
            }
        });
    }

    //popup 去提问
    function goQuestionFn(teacherId,questionfee,isquestion,name) {
        isLogin(function () {
            removeQuestionForm();//清空提问form表单
            $.ajax({
                url: baseloaction + "/mobile/uc/qa/type/findQaTypeByTeacherId",
                data:{"teacherId": teacherId},
                type:"post",
                dataType:"json",
                success:function (result) {
                    if(result.success){
                        $("#questionType").val(result.entity.typeName).prop("readonly",true);
                        $("#question-type").val(result.entity.id);
                        $("#teacher-id").val(teacherId);
                        $("#questionFee").val(questionfee);
                        $("#isQuestion").val(isquestion);
                        $("#teacher_name").val(name);
                        $.popup('.toQuestionPopup');
                    }else {
                        $.toast(result.message);
                    }
                },
                error:function () {
                    $.toast("系统繁忙，请稍后重试");
                }
            });
        });

    }

    function removeQuestionForm() {
        $("#tqImgWrap>span").remove();
        $("#tqImgWrap").append('<span id="def-span-box"><img src="' + staticPath + '/front/web/v3/img/default/default-course.gif" height="50px" width="80px"/></span>');
        $("#questionType").val("");
        $("#question-context").val("");
        $("#imageStr").val("");
    }
})